package com.wangbo.minio;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import lombok.SneakyThrows;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class MinioUtil {

    /**
     * bucket是否存在
     */
    @SneakyThrows
    public static boolean bucketExists(MinioClient minioClient, String bucketName) {
        return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    /**
     * 创建bucket
     */
    @SneakyThrows
    public static void makeBucket(MinioClient minioClient, String bucketName) {
        if (!bucketExists(minioClient, bucketName)) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    /**
     * 获取全部buckets列表
     */
    @SneakyThrows
    public static List<Bucket> getAllBuckets(MinioClient minioClient) {
        return minioClient.listBuckets();
    }

    /**
     * 上传文件
     */
    @SneakyThrows
    public static String uploadFile(MinioClient minioClient, String bucketName, String filePath, InputStream inputStream, String contentType, int duration) {
        minioClient.putObject(
                PutObjectArgs
                        .builder()
                        .bucket(bucketName)
                        .object(filePath)
                        .stream(inputStream, -1L, 10485760L)
                        .contentType(contentType)
                        .build());

        return getFileUrl(minioClient, bucketName, filePath, duration);
    }

    /**
     * 获取文件URL
     */
    @SneakyThrows
    public static String getFileUrl(MinioClient minioClient, String bucketName, String filePath, int duration) {
        Map<String, String> reqParams = new HashMap<>();
        reqParams.put("response-content-type", "application/octet-stream");
        return minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs
                        .builder()
                        .method(Method.GET)
                        .bucket(bucketName)
                        .object(filePath)
                        .expiry(duration, TimeUnit.DAYS)
                        .extraQueryParams(reqParams)
                        .build());
    }

    /**
     * 获取 object
     */
    @SneakyThrows
    public static byte[] getObject(MinioClient minioClient, String bucketName, String filePath) {
        try (InputStream inputStream = minioClient.getObject(
                GetObjectArgs
                        .builder()
                        .bucket(bucketName)
                        .object(filePath)
                        .build())) {
            return IoUtil.readBytes(inputStream);
        }
    }

    /**
     *
     */
    public static void removeObject(MinioClient minioClient, String bucketName, String filePath) {

    }

}
